from src.config import Config
import sqlite3
import os

class Database:

    def __init__(self):
        cfg = Config()
        self.hbase = sqlite3.connect(cfg.cache_dir_path+'/history.db', check_same_thread=False)
        self.hcursor = self.hbase.cursor()

        self.hcursor.execute("""CREATE TABLE IF NOT EXISTS history (
            video TEXT,
            videoId TEXT
        )""")
        self.hbase.commit()

        self.pbase = sqlite3.connect(cfg.cache_dir_path+'/playlists.db', check_same_thread=False)
        self.pcursor = self.pbase.cursor()

        self.pcursor.execute("""CREATE TABLE IF NOT EXISTS playlists (
            name TEXT,
            videos TEXT
        )""")
        self.pbase.commit()

    def insert_video_in_history(self, hdict):
        if 'videoId' in hdict.keys():
            video = (str(hdict), hdict['videoId'])
        else:
            video = (str(hdict), hdict['url'])

        self.hcursor.execute("INSERT INTO history VALUES (?, ?)", video)
        self.hbase.commit()

    def delete_video_from_history(self, hdict):
        if 'videoId' in hdict.keys():
            videoId = (str(hdict['videoId']),)
        else:
            videoId = (str(hdict['url']),)

        self.hcursor.execute("DELETE FROM history WHERE videoId = (?)", videoId)
        self.hbase.commit()

    def load_history(self):
        return self.hcursor.execute("SELECT * FROM history")


    def get_user_playlist(self, name: str):
        return self.pcursor.execute("SELECT videos FROM playlists WHERE name = (?)", (name,)).fetchone()

    def insert_user_playlist(self, name: str, videos: str):
        playlist = (name, videos)
        self.pcursor.execute("INSERT INTO playlists VALUES (?, ?)", playlist)
        self.pbase.commit()

    def load_user_playlists(self):
        return self.pcursor.execute("SELECT * FROM playlists")     

    def remove_user_playlist(self, name: str):
        name = (name,)
        self.pcursor.execute("DELETE FROM playlists WHERE name = (?)", name)
        self.pbase.commit()


